##########################################################################################################################################
###### This is the file containing the merger regression results with betas based on daily data
###############################
# It creates the final resultsfor the two final columns of Table 12
# Please note that in some instances, the paper contains some formatting modifications
# such as a "log()" that is not automatically added here or that we present the negative
# of tsim, while most output here is generated for the positive

# This is just the final step. There are other code files that are used for data preparation
# This processed data are saved and loaded in this code



# set to your working directory:
setwd("C:\\Users\\Admin\\OneDrive\\Desktop\\Market Power and Systematic Risk - Data and Code")
getwd()
###################################
load("Mergers_with_SIC_NEW.RData")


Mergers_New$YearMonth = as.numeric(paste0(format(Mergers_New$Date.Effective.or.Unconditional,"%Y"),format(Mergers_New$Date.Effective.or.Unconditional,"%m")))
Mergers_New$YearMonth_ann = as.numeric(paste0(format(Mergers_New$Date.Announced,"%Y"),format(Mergers_New$Date.Announced,"%m")))
Mergers_New = Mergers_New[Mergers_New$Date.Announced>="1989-01-01",]

Mergers_New = Mergers_New[Mergers_New$Deal.Status == "Completed",]

Mergers_New = Mergers_New[Mergers_New$Percentage.of.Shares.Held.at.Announcement<10 | is.na(Mergers_New$Percentage.of.Shares.Held.at.Announcement),]

#only obtain mergers where at least 50 % of the Stock was Aquired:
Mergers_New = Mergers_New[Mergers_New$Percentage.of.Shares.Acquired.in.Transaction > 50 | is.na(Mergers_New$Percentage.of.Shares.Acquired.in.Transaction), ]

#Specify the M.A.Type
Mergers_New = Mergers_New[Mergers_New$M.A.Type == "Disclosed Dollar Value Deal" | 
                            Mergers_New$M.A.Type == "Undisclosed Dollar Value Deal",]

sum(is.na(Mergers_New$Acquiror.6.digit.CUSIP))


Mergers_New = Mergers_New[Mergers_New$Acquiror.6.digit.CUSIP != Mergers_New$Target.6.digit.CUSIP & !is.na(Mergers_New$Acquiror.6.digit.CUSIP),]

################################ Specifications #########################################################

Mergers_New = Mergers_New[apply(sapply(c("Acquire competitors technology/strategic assets",
                                         "Strengthen existing operations/expand presence in primary market",
                                         "Strengthen operations", "Create synergies", "Concentrate on core businesses/assets"), 
                                       grepl, Mergers_New$Purpose),1,any),]

############################################ Merger_Load.R ########################################################## 

load("Control_Panel_Daily.RData")

Panel_New<-Panel_New[order(Panel_New$YearMonth),]

Panel_New$six_digit_cusip = substr(Panel_New$cusip,1,6)

Mergers_New = Mergers_New[Mergers_New$Acquiror.6.digit.CUSIP%in%Panel_New$six_digit_cusip,]
Mergers_New$Year=floor(Mergers_New$YearMonth/100)
Mergers_New$Year=Mergers_New$Year+1
Mergers_New$Year2=Mergers_New$Year+1

############################################
#########
Panel_New_all = merge(Panel_New,Mergers_New,by.x=c("YearMonth","six_digit_cusip"),by.y=c("YearMonth","Acquiror.6.digit.CUSIP"),all.x=T)
#######################################################

# to use announcement dates instead:

Panel_New_all$COMNAM = NULL
Panel_New_all$conm = NULL
Panel_New_all$tic = NULL
Panel_New_all$TICKER = NULL

#Construct the Dummy for each Company/Year
################################################
Panel_New_all$Merger_Dummy = ifelse(is.na(Panel_New_all$Date.Effective.or.Unconditional),0,1)
###########################################################

sum(Panel_New_all$Merger_Dummy)
library(data.table)
setDT(Panel_New_all)
Panel_New_all = Panel_New_all[order(Panel_New_all$Time, decreasing = F),]

ExtAeND = function(x,days){
  #At this Point in Time a merger happened
  a = which(x==1)
  if(length(a)>1){
    b = pmin(which(x==1) + days,length(x))
    c = mapply(seq,a,b,SIMPLIFY = F)
    x[unique(unlist(c))] = 1
  }
  
  return(x)
}
ExtAeNDb = function(x,days){
  #At this Point in Time a merger happened
  a = which(x!=0)
  if(length(a)>1){
    b = pmin(which(x!=0) + days,length(x))
    for(i in 1:length(a)){
      x[a[i]:b[i]]<-x[a[i]]
    }
  }
  return(x)
}

qcut <- function(x, n) {
  cut(x, quantile(x, seq(0, 1, length = n + 1),'na.rm' = TRUE), labels = seq_len(n),
      include.lowest = TRUE)
}

Panel_New_all$Merger_Dummy24<-Panel_New_all$Merger_Dummy

Panel_New_all[,Merger_Dummy24:=ExtAeND(Merger_Dummy24,24),by=six_digit_cusip]


#Conduct the Panel Regressions:
setDF(Panel_New_all)
Panel_New_all$year=Panel_New_all$year.x


source("Table_Functions.R")


#Daily Stuff:

setDF(Panel_New_all)
Temp = Panel_New_all[,c("Time","YearMonth","year","NAICS","PERMNO","Weighting_Beta_M_60M","Weighting_Beta_M_24M","HHI","prodmktfluid","tnic3hhi","tnic3tsimm","Age","Momentum","Illiquidity","MktCap","Mkt_Book","Default_Spread",
                        "Financial_Leverage", "Operating_Leverage","Firm_size","InvestmentRates","ROE","Logat","Dividend_Dummy","q","I_Vol","Merger_Dummy","Merger_Dummy24")]#

library(lfe)
for(i in 1:dim(Temp)[2]){
  Temp[,i][Temp[,i] == Inf] = NA
  Temp[,i][Temp[,i] == -Inf] = NA
}
Temp = na.omit(Temp)

A = felm(Weighting_Beta_M_60M ~ Merger_Dummy24 + scale(log(Age)) + scale(Logat) + scale(Default_Spread) + Dividend_Dummy + scale(Financial_Leverage) + scale(log(MktCap)) + scale(Illiquidity) + scale(InvestmentRates) + scale(I_Vol) +  
           scale(log(Mkt_Book)) + scale(Momentum)  + scale(Operating_Leverage) +  scale(q)  + scale(ROE)  | PERMNO + year | 0 | NAICS + year, data = Temp, cmethod="reghdfe")

B = felm(Weighting_Beta_M_24M ~ Merger_Dummy24 + scale(log(Age)) + scale(Logat) + scale(Default_Spread) + Dividend_Dummy + scale(Financial_Leverage) + scale(log(MktCap)) + scale(Illiquidity) + scale(InvestmentRates) + scale(I_Vol) +  
           scale(log(Mkt_Book)) + scale(Momentum)  + scale(Operating_Leverage) +  scale(q)  + scale(ROE)  | PERMNO + year | 0 | NAICS + year, data = Temp, cmethod="reghdfe")


Names = c("Merger_Dummy","Age","AT","Default spread","Dividend","Financial leverage","Firm size","Illiquidity","Investment rate","iVol",
          "Mkt/Book","Momentum","Operating leverage","q","ROE")

Result = data.frame(Names=rep(NA,2*length(summary(A)$coef[,1])+2),'Weighting 60 Months'=rep(NA,2*length(summary(A)$coef[,1])+2),'Weighting 24 Months' = rep(NA,2*length(summary(A)$coef[,1])+2))

Result$Names[seq(from=1,to=(nrow(Result)-2),by=2)] = Names

Result$Weighting.60.Months[seq(from=1,to=(nrow(Result)-2),by=2)] = paste0(as.character(Lag_zero(round(summary(A)$coefficients[,1],digits=3),digits=3)),star_function(summary(A)$coefficients[,4]))
Result$Weighting.60.Months[seq(from=2,to=(nrow(Result)-2),by=2)] = paste0("(",Lag_zero(round(summary(A)$coefficients[,3],digits=3),digits=3),")")
Result$Weighting.60.Months[nrow(Result)-1] = Lag_zero(round(summary(A)$r.sq * 100, digits = 2),digits=2)
Result$Weighting.60.Months[nrow(Result)] = nrow(Mergers_New)

Result$Weighting.24.Months[seq(from=1,to=(nrow(Result)-2),by=2)] = paste0(as.character(Lag_zero(round(summary(B)$coefficients[,1],digits=3),digits=3)),star_function(summary(B)$coefficients[,4]))
Result$Weighting.24.Months[seq(from=2,to=(nrow(Result)-2),by=2)] = paste0("(",Lag_zero(round(summary(B)$coefficients[,3],digits=3),digits=3),")")
Result$Weighting.24.Months[nrow(Result)-1] = Lag_zero(round(summary(B)$r.sq * 100, digits = 2),digits=2)
Result$Weighting.24.Months[nrow(Result)] = nrow(Mergers_New)

library(xtable)
print(xtable(Result),include.rownames=F,sanitize.text.function=function(x){x})





